package com.yto.cn.map.map;

/**
 * @author dongxing
 **/
public class MyHashMap<K,V>{

    private Entry[] table;
    private static Integer CAPATRY = 8;
    private Integer size=0;


    public MyHashMap() {
        this.table = new Entry[CAPATRY];
    }

    public int size() {
        return this.size;
    }

    public V get(K key) {

        //算出下标位置
        int hashCode = key.hashCode();
        int index = hashCode % CAPATRY;

        for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
            if (entry.k.equals(key)) {
                return entry.v;
            }
        }
        return null;
    }

    public V put(K key, V value) {

        int hash = key.hashCode();
        int index = hash % CAPATRY;

        for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
            if (entry.k.equals(key)) {
                V oldValue = entry.v;
                entry.v = value;
                return oldValue;
            }
        }
        //添加进去
        addEntry(key, value, index);
        size++;
        return null;
    }

    private void addEntry(K key, V value, int index) {
        Entry entry = new Entry(key, value, table[index]);
        table[index] = entry;
    }

    class Entry<K,V>{
        private K k;
        private V v;
        private Entry next;

        public Entry(K k, V v, Entry next) {
            this.k = k;
            this.v = v;
            this.next = next;
        }

        public K getK() {
            return k;
        }

        public void setK(K k) {
            this.k = k;
        }

        public V getV() {
            return v;
        }

        public void setV(V v) {
            this.v = v;
        }

        public Entry getNext() {
            return next;
        }

        public void setNext(Entry next) {
            this.next = next;
        }
    }

    public static void main(String[] args) {
        MyHashMap<Object, Object> objectObjectMyHashMap = new MyHashMap<>();
        for (int i = 0; i < 10; i++) {
            objectObjectMyHashMap.put("周瑜" + i, "lo" + i);
        }
        Object o = objectObjectMyHashMap.get("周瑜" + 4);
        System.out.println(o);
    }
}
